package com.gwsdk.paysdk.bean;

import android.app.Activity;
import android.app.Dialog;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;

import com.gwsdk.open.FlagControl;
import com.gwsdk.open.LogoutCallback;
import com.gwsdk.open.GWApi;
import com.gwsdk.paysdk.common.Constant;
import com.gwsdk.paysdk.dialog.DialogUtil;
import com.gwsdk.paysdk.dialog.realname.GWCertificationDialog;
import com.gwsdk.paysdk.dialog.realname.GWRealNameDialog;
import com.gwsdk.paysdk.entity.AntiAddiction;
import com.gwsdk.paysdk.http.process.AntiAddictionProgress;
import com.gwsdk.paysdk.http.process.GetAgeResultProcess;
import com.gwsdk.paysdk.http.process.UploadTalkingCodeProcess;
import com.gwsdk.paysdk.listener.OnMultiClickListener;
import com.gwsdk.paysdk.utils.AppUtils;
import com.gwsdk.paysdk.utils.GWLog;
import com.gwsdk.paysdk.utils.MyTimeUtil;
import com.gwsdk.paysdk.utils.SharedPreferencesUtils;
import com.gwsdk.paysdk.utils.TextUtils;

/**
 * Created by Administrator on 2017/5/5.
 * 防沉迷
 */

public class AntiAddictionModel {

    public static final String TAG = "AntiAddictionModel";

    public static MyTimeUtil myTimeUtil;
    private GamePlayFinishTimer gameTimer;

    private static AntiAddictionModel instance;
    private Activity mContext;
    public GWCertificationDialog certificationDialog;

    public AntiAddictionModel() {
    }

    public static AntiAddictionModel getInstance() {
        if (instance == null) {
            instance = new AntiAddictionModel();
        }
        return instance;
    }


    /**
     * 请求防沉迷信息
     */
    public void requestAntiAddictionInfo(Activity activity) {
        this.mContext = activity;
        GWLog.w(TAG, "requestAntiAddictionInfo-" + FlagControl.isLogin + "-" + !Constant.userIsOnLine + "-" + Constant.showedNoteDialog);
        if (FlagControl.isLogin && !Constant.userIsOnLine && Constant.showedNoteDialog){
            GWLog.w(TAG, "不请求用户上线和防沉迷信息");
            AntiAddictionProgress antiAddictionProgress = new AntiAddictionProgress();
            antiAddictionProgress.setGet_talking_code(1);
            antiAddictionProgress.post(mHandler);
        }
    }


    /**
     * 请求防沉迷信息handler
     */
    private final Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constant.REQUEST_ANTI_ADDICTION_SUCCESS:
                    GWLog.w(TAG, "请求防沉迷信息成功");
                    Constant.userIsOnLine = true; //用户改为在线状态
                    handlerRealnameInfo((AntiAddiction) msg.obj);
                    break;

                case Constant.REQUEST_ANTI_ADDICTION_FAIL:
                    //请求防沉迷信息失败
                    GWLog.e(TAG, "请求防沉迷信息失败，不进入防沉迷");
                    break;
            }
        }
    };

    public void handlerRealnameInfo(AntiAddiction antiAddiction) {
        if (antiAddiction == null) {
            GWLog.e(TAG, "msg.obj is null");
            return;
        }

        if (antiAddiction.getAge_status() == 4){
            GWLog.w(TAG, "认证状态为等待中，重新查询认证状态");
            new GetAgeResultProcess().post();
        }

        if (antiAddiction.getAge_status() == 2) {
            GWLog.w(TAG, "玩家已认证并且已成年，不进入防沉迷限制");
            return;
        }

        if (Constant.CountryAge == 0) {//走平台实名认证
            GWLog.w(TAG, "当前帐号没认证，弹出认证框");
            showCertificationDialog(antiAddiction);
        }else if (Constant.CountryAge == 1) {//开启了国家实名
            GWLog.w(TAG, "开启了国家认证，上报上报Talking_Code：" + antiAddiction.getTalking_code());
            countryRealname(antiAddiction);
        }

        if (antiAddiction.getOnoff().equals("1")) {
            if ("1".equals(antiAddiction.getPreventWay()) && antiAddiction.getAge_status() == 3) {
                if (antiAddiction.getSurplusSecond() == 0) {
                    exitGame();
                }else {
                    startGameTimer(antiAddiction.getSurplusSecond());
                }
            }else if ("2".equals(antiAddiction.getPreventWay())) {
                GWLog.w(TAG, "防沉迷开启，玩家认证状态为:"+antiAddiction.getAge_status() + "，开始计时");
                startTime(antiAddiction);

                if (antiAddiction.getAge_status() == 3 && antiAddiction.getOnoff().equals("1")) {
                    if (AppUtils.getDouble(antiAddiction.getBat()) > 0 &&
                            antiAddiction.getPlay_time() >= AppUtils.getDouble(antiAddiction.getBat())) { //当前玩家已经超时
                        GWLog.w(TAG, "已认证未成年，开启了防沉迷，已超时弹出下线弹窗");
                        showDownDialog(GWApi.getApi().getLogoutClaaback(), "由于您未成年，当前游戏时长已到达防沉迷限制，请下线休息");
                    }
                }
            }
        }
    }

    private void countryRealname(AntiAddiction antiAddiction) {
        if (TextUtils.isEmpty(antiAddiction.getTalking_code())){
            return;
        }
        Constant.Talking_Code = antiAddiction.getTalking_code();

        UploadTalkingCodeProcess process = new UploadTalkingCodeProcess(); //上线 上报Talking_Code
        process.setLogin_type(1);
        process.setTalking_code(antiAddiction.getTalking_code());
        process.post();

        GWLog.w(TAG, "开启国家认证，当前帐号没认证，弹出认证框");
        showCertificationDialog(antiAddiction);
    }

    private void showCertificationDialog(AntiAddiction antiAddiction) {
        //未审核，或者开关关闭
        if (antiAddiction.getAge_status() != 0 || antiAddiction.getAuth() == 0) {
            return;
        }
        if (certificationDialog == null){
            certificationDialog = new GWCertificationDialog(mContext, antiAddiction.getContents_off(), false);
            certificationDialog.show();
        }
    }

    //强制下线提示弹窗,注销登录
    public void showDownDialog(final LogoutCallback logoutCallback, String msg){
        Dialog dialog = DialogUtil.gw_down_time_alert(mContext, msg, "确定",  new OnMultiClickListener() {
                    @Override
                    public void onMultiClick(View v) {
                        InitModel.init().offLine(mContext, true);
                        if (logoutCallback != null) {
                            try {
                                SharedPreferencesUtils.getInstance().setIsLogout(mContext,true);     //注销状态设为trueThread.sleep(500);
                                PersonalCenterModel.getInstance().clearUserInfoAll();
                                Thread.sleep(100);

                                logoutCallback.logoutResult("1");
                                FlagControl.flag = true;
                                FlagControl.isLogin = false;
                                FlagControl.isFloatingOpen = false;
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        if (certificationDialog != null){
                            certificationDialog = null; //这里要把认证弹窗设置为null，否则不弹出
                        }
                    }
                }
        );

        dialog.setCancelable(false);
        dialog.show();
    }


    /**
     * 开始计时
     */
    public void startTime(AntiAddiction antiAddiction){
        if (myTimeUtil == null) {
            myTimeUtil = new MyTimeUtil(mContext, antiAddiction);
        }
        myTimeUtil.start(antiAddiction);
    }


    /**
     * 停止计时，恢复状态
     */
    public void stopTime(boolean isLogout){
        if (isLogout && certificationDialog != null){ //如果是注销登录操作，把实名弹窗设置为null，下次回到游戏界面可以弹出
            certificationDialog.dismiss();
            certificationDialog = null;
        }
        if(myTimeUtil != null){
            myTimeUtil.Stop();
            myTimeUtil = null;
        }
    }

    private void exitGame() {
        new GWRealNameDialog.Builder()
                .show(GWApi.getApi().getContext(),
                        GWApi.getApi().getContext().getFragmentManager());
    }

    private void startGameTimer(long second) {
        gameTimer = new GamePlayFinishTimer(second * 1000, 1000);
        gameTimer.start();
    }

    public void stopGameTimer() {
        if(gameTimer != null){
            gameTimer.cancel();
            gameTimer = null;
        }
    }

    class GamePlayFinishTimer extends CountDownTimer {

        public GamePlayFinishTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onTick(long millisUntilFinished) { }

        @Override
        public void onFinish() {// 计时完毕时触发
            GWLog.e(TAG,"到了提醒时间");
            exitGame();
        }
    }

}
